package com.jlect.swebing.renderers.gwt.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;

/**
 * {@todo set description}
 *
 * @author Sergey Kozmin
 * @since 16.11.2007 10:04:31
 */
public class DebugUtils {

    private DebugUtils() {
        // hide constructor because we are a utility class with static methods only.
    }

    public static void initDebugAndErrorHandling() {
//        Debug.enable();
//        DebugConsole.getInstance().disable(); // can be enabled for web mode
        GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
            public void onUncaughtException(final Throwable tracepoint) {
                performDefaultErrorHandling(tracepoint);
            }
        });
    }

    public static void performDefaultErrorHandling(final Throwable caught) {
        GWT.log("Error occured.", caught);
        if (caught != null) {
            final String stacktrace = DebugUtils.getStacktraceAsString(caught);
            caught.printStackTrace(System.err);
            Window.alert(stacktrace);
        } else {
            final String message = "Error ocuured, but we have no further information about the cause";
            Window.alert(message);
        }
    }

    public static String getStacktraceAsString(final Throwable tracepoint) {
        final StackTraceElement[] trace = tracepoint.getStackTrace();
        final StringBuffer sbuf = new StringBuffer(2048);
        sbuf.append(tracepoint.toString());
        sbuf.append(": at\n");
        // I cut the stacktrace at depth 7
        final int length = Math.min(7, trace.length);
        for (int i = 0; i <= length; i++) {
            sbuf.append(trace[i].toString());
            sbuf.append("\n");
        }
        if (trace.length > 7) {
            sbuf.append("...");
        }
        final String stacktrace = sbuf.toString();
        return stacktrace;
    }

}